package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.config.RestHighLevelClientConfig;
import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;

import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;

import org.elasticsearch.common.geo.GeoPoint;

import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;

import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;

import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;

import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClientConfig clientConfig;

    /**
     * 酒店搜索功能
     * @param params 请求参数对象 包含用户输入的关键字
     * @return
     */
    @Override
    public PageResult search(RequestParams params) {
        try {
            //准备request对象 传入索引名
            SearchRequest request = new SearchRequest("hotel");
            //构建查询条件
             buildBasicQuery(params, request);

             //高亮查询
             request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));

            // 设置分页条件
            Integer page = params.getPage();
            Integer size = params.getSize();
            request.source().from((page-1)*size);
            request.source().size(size);

            //排序规则 根据前端传来的选择不同 排序的字段不同
            String sortBy = params.getSortBy();
            if("price".equals(sortBy)){
                request.source().sort("price",SortOrder.ASC);
            }else if ("score".equals(sortBy)){
                request.source().sort("score",SortOrder.DESC);
            }

            //按照距离排序
            String location = params.getLocation();
            if(StringUtils.isNotBlank(location)){
                request.source().sort(SortBuilders
                        .geoDistanceSort("location",new GeoPoint(location))
                        .order(SortOrder.ASC)
                        .unit(DistanceUnit.KILOMETERS));
            }

            //发送请求 得到响应
            SearchResponse response = clientConfig.client().search(request, RequestOptions.DEFAULT);
            //解析结果 并返回结果
            return getPageResult(response);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解析数据
     * @param response
     * @return
     */
    private PageResult getPageResult(SearchResponse response) {
        //设置响应结果
        SearchHits hits = response.getHits();
        PageResult pageResult = new PageResult();
        //设置响应的查询总数量
        pageResult.setTotal(hits.getTotalHits().value);

        //创建集合 将查询到的文档放入java集合中
        List<HotelDoc> list = new ArrayList<>();
        //遍历文档
        for (SearchHit hit : hits) {
            //将json文档转换为java对象
            HotelDoc hotelDoc = JSON.parseObject(hit.getSourceAsString(), HotelDoc.class);
            //获取排序值
            Object[] sortValues = hit.getSortValues();
            if(sortValues.length > 0){
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }
            //获取高亮值
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if(!CollectionUtils.isEmpty(highlightFields)){
               //根据字段名 获取高亮结果
                HighlightField highlightField = highlightFields.get("name");
                if(highlightField != null){
                    //获取高亮后的值
                    String string = highlightField.getFragments()[0].string();
                    //覆盖非高亮结果
                    hotelDoc.setName(string);
                }
            }


            list.add(hotelDoc);
        }
        pageResult.setHotels(list);
        return pageResult;
    }

    /**
     * 设置条件
     * @param params
     * @param request
     * @throws IOException
     */
    private void buildBasicQuery(RequestParams params, SearchRequest request) throws IOException {

        //1.构建BooleanQuery
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        //2.关键字搜索
        String paramsKey = params.getKey();
        if (StringUtils.isBlank(paramsKey)) {
            //如果用户未输入关键字搜索 就查询全部
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        } else {
            //如果不为空就在all字段中查找
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", paramsKey));
        }

        //3.城市条件
        if(StringUtils.isNotBlank(params.getCity())){
            boolQueryBuilder.filter(QueryBuilders.termQuery("city",params.getCity()));
        }

        //4.品牌条件
        if(StringUtils.isNotBlank(params.getBrand())){
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand",params.getBrand()));
        }

        //5.星级条件
        if(StringUtils.isNotBlank(params.getStarName())){
            if(params.getStarName().equals("五星"))params.setStarName("五星级");
            if(params.getStarName().equals("四星"))params.setStarName("四星级");
            boolQueryBuilder.filter(QueryBuilders.termQuery("starName",params.getStarName()));
        }

        //6.价格范围查询
        if(params.getMaxPrice() !=null && params.getMinPrice() != null ){
            boolQueryBuilder.filter(QueryBuilders
                    .rangeQuery("price")
                    .gte(params.getMinPrice()) //最小价格
                    .lte(params.getMaxPrice()));//最大价格
        }

        //算分控制
        FunctionScoreQueryBuilder functionScoreQueryBuilder =QueryBuilders.functionScoreQuery(
                //原始查询,相关性算法的查询
                boolQueryBuilder,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        // 其中的一个function score 元素
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                //过滤条件
                                QueryBuilders.termQuery("isAD",true),
                                //算分函数
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
                });

        request.source().query(functionScoreQueryBuilder);
    }

    //动态获取城市列表 星级列表 品牌列表
    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        try {
            //准备Request
            SearchRequest request = new SearchRequest("hotel");
            //准备DSL
            buildBasicQuery(params,request);

            //设置size
            request.source().size(0);
            //聚合条件设置
            buildAggregation(request);
            //发出请求
            SearchResponse response = clientConfig.client().search(request, RequestOptions.DEFAULT);

            //解析结果
            Map<String,List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            //根据品牌名称 获取品牌结果
            List<String> brandAgg = getAggByName(aggregations, "brandAgg");
            result.put("brand",brandAgg);
            //根据城市名称 获取聚合结果
            List<String> cityAgg = getAggByName(aggregations, "cityAgg");
            result.put("city",cityAgg);
            //根据星级聚合名称 获取结果
            List<String> starAgg = getAggByName(aggregations, "starAgg");
            result.put("starName",starAgg);

            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //搜索框自动补全
    @Override
    public List<String> getSuggestions(String key) {
        try {
            //准备Request
            SearchRequest request = new SearchRequest("hotel");
            //准备DSL
            request.source().suggest(new SuggestBuilder().addSuggestion(
                            "suggestions",//自定义名称
                                  SuggestBuilders.completionSuggestion("suggestion")//自动补全的字段
                                        .prefix(key)
                                        .skipDuplicates(true) // 去除重复的结果
                                        .size(10)// 结果显示的数量
            ));

            //发起请求
            SearchResponse response = clientConfig.client().search(request, RequestOptions.DEFAULT);

            //解析结果
            Suggest suggest = response.getSuggest();
            //根据补全查询名称,获取补全结果
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            //获取options
//            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
//            List<String> list = new ArrayList<>();
//            for (CompletionSuggestion.Entry.Option option : options) {
//                Text text = option.getText();
//                list.add(text.toString());
//            }
            //遍历
            List<String> list = suggestions.getOptions()
                                                .stream()
                                                .map(option -> option.getText().toString())
                                                .collect(Collectors.toList());

            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //聚合条件设置
    private void buildAggregation(SearchRequest request){
        request.source().aggregation(AggregationBuilders
                                        .terms("brandAgg")
                                        .field("brand")
                                        .size(20));

        request.source().aggregation(AggregationBuilders
                                        .terms("cityAgg")
                                        .field("city")
                                        .size(20));

        request.source().aggregation(AggregationBuilders
                                        .terms("starAgg")
                                        .field("starName")
                                        .size(20));
    }
    //根据聚合名称获取对应的聚合数据
    private List<String> getAggByName(Aggregations aggregations, String aggName){
        //4.1根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);

        //4.2 获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        // 4.3.遍历
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            // 4.4.获取key
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }

    @Override
    public void deleteById(Long id) {
        try {
            //准备Request
            DeleteRequest request = new DeleteRequest("hotel",id.toString());
            //发送请求
            clientConfig.client().delete(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void insertById(Long id) {
        try {
            //根据id 查询酒店数据
            Hotel hotel = getById(id);
            //转换为文档类型
            HotelDoc hotelDoc = new HotelDoc(hotel);
            //准备Request对象
            IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
            //准备json文档
            request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
            //发送请求
            clientConfig.client().index(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
